package com.lingchou.cloud.process.client.controller;

import com.lc.common.bean.response.Result;
import com.lingchou.cloud.process.api.controller.ProcessStartApi;
import com.lingchou.cloud.process.api.dto.result.ProcessInstanceDTO;
import com.lingchou.cloud.process.api.enums.CommentTypeEnum;
import com.lingchou.cloud.process.client.service.FlowAbleCommentService;
import com.lingchou.cloud.process.client.service.ProcessCheckService;
import com.lingchou.cloud.process.client.service.ProcessUtilService;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 流程启动API实现
 *
 * @author LingChou
 */
@RestController
@Validated
public class ProcessStartApiImpl implements ProcessStartApi {
    private final RuntimeService runtimeService;
    private final IdentityService identityService;
    private final ProcessUtilService processUtilService;
    private final ProcessCheckService processCheckService;
    private final FlowAbleCommentService flowAbleCommentService;

    public ProcessStartApiImpl(RuntimeService runtimeService, IdentityService identityService, ProcessUtilService processUtilService, ProcessCheckService processCheckService, FlowAbleCommentService flowAbleCommentService) {
        this.runtimeService = runtimeService;
        this.identityService = identityService;
        this.processUtilService = processUtilService;
        this.processCheckService = processCheckService;
        this.flowAbleCommentService = flowAbleCommentService;
    }

    @Override
    public Result<ProcessInstanceDTO> startInstanceByDefinitionId(String definitionId, String userId, String typeId, Map<String, Object> params) {
        if (processCheckService.checkDefinitionInvalid(definitionId)) {
            return Result.failure("流程定义无效");
        }
        identityService.setAuthenticatedUserId(userId);
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(definitionId, typeId, params);
        //4.添加审批记录
        flowAbleCommentService.addComment(null, userId, processInstance.getProcessInstanceId(),
                CommentTypeEnum.SUBMIT.toString(), "发起流程");
        return processUtilService.packageReturnProcessInstance(processInstance, "流程启动失败");
    }

    @Override
    public Result<String> getUserId() {
        String userId = Authentication.getAuthenticatedUserId();
        return Result.success(userId);
    }


}
